<script setup>
import {computed, getCurrentInstance, reactive, ref, toRefs, watch} from "vue";
import SelectInspectBasis from "@/views/lims/contractAnalysis/table/selectTable.vue";
import SubjectTable from "@/views/lims/contractAnalysis/table/detailTable.vue";
import WanFengSelect from "@/components/wanfengComponents/WanFengSelect.vue";
import {LimsConfig, LimsFilters} from "@/api/lims/common/LimsModel";
import {getTableRecord} from "@/api/lims/sysManager/table";
import moment from "moment";

const inspectBasisTable = ref(null)

const props = defineProps({form: Object})
const emit = defineEmits(['setting-payment'])
const {form} = toRefs(props)
const {proxy} = getCurrentInstance()
/**
 * 产品标称：只查询产品标准
 * 委托指定：查询产品标准，和方法标准
 * 检验机构确定：查询产品标准和方法标准
 */
const handleSelectInspectBasis = () => {
  let table = {
    tableName: 'S_MATERIAL',
    columns: [
      {label: '标识', name: 'IDENTITY', isQuery: true},
      {label: '名称', name: 'NAME', isQuery: true},
      {label: '描述', name: 'DESCRIPTION', isQuery: true},
      {label: '产品标准', name: 'PRODUCT_NAME', isQuery: true},
      {label: '产品规格', name: 'PRODUCT_SPEC', isQuery: true},
      {label: '产品类型', name: 'PRODUCT_TYPE', isQuery: true},
    ],
    height: 450,
  }
  if (!form.value.INSPECT_BASIS) {
    proxy.$modal.msg('请选择依据类型')
    return
  }
  if (form.value.INSPECT_BASIS === '产品标称') {
    inspectBasisTable.value.show(table)
  } else {
    let queryColumns = [
      {label: '标识', name: '[IDENTITY]', isQuery: true},
      {label: '名称', name: 'NAME', isQuery: true},
      {label: '描述', name: 'DESCRIPTION', isQuery: true},
      {label: '标准号', name: 'STANDARD_CODE', isQuery: true},
      {label: '标准类型', name: 'STAND_TYPE', isQuery: true},
    ]
    let querySql = "select [IDENTITY], NAME, DESCRIPTION,PRODUCT_NAME AS STANDARD_CODE, N'产品标准' as STAND_TYPE FROM S_MATERIAL ";
    querySql += " UNION "
    querySql += "SELECT [IDENTITY], NAME, DESCRIPTION, STANDARD_CODE, N'方法标准' as STAND_TYPE FROM S_METHOD "
    querySql = "select * from (" + querySql + ") t"
    querySql += " WHERE 1=1 "
    inspectBasisTable.value.selectBySql(querySql, queryColumns, true);
  }
}
const selectedInspectBasis = (val) => {
  if (form.value.INSPECT_BASIS === '产品标称'){
    form.value.INSPECT_BASIS_VALUE = val.PRODUCT_NAME
  }else {
    form.value.INSPECT_BASIS_VALUE = val.STANDARD_CODE

  }
}

const inspectProjectList = ref([])


const subProjects = ref([])


/**
 * 计算费用
 */
const computedFee = () => {
  let charges = []
  let totalFee = 0;
  //1.计算检测项目费用
  let inspectFee = 0
  inspectProjectList.value.forEach(item => {
    let price = parseFloat(item.SUBJECT_PRICE)
    if (price && !isNaN(price)) {
      totalFee = price + totalFee
      inspectFee += price
    }
  })
  charges.push({chargeName:'检验费用', chargeFee: inspectFee, index: 1})
  //1.1加急费用
  if (form.value.INSPECT_CYCLE) {
    let urgentFee = {chargeName:'加急费用', chargeFee: 0, index: 2}
    urgentOptions.value.forEach(item => {
      if (item.ID === form.value.INSPECT_CYCLE) {
        let upPrice = parseFloat(item.UP_PRICE) * 0.01
        let upFee = totalFee * upPrice
        totalFee = totalFee + upFee
        urgentFee.chargeFee = upFee
      }
    })
    charges.push(urgentFee)
  }
  //2.余样处理费
  if (form.value.INSPECT_REMAINING_SAMPLE_HANDLE === '承检机构处理(需收取50元样品处理费)') {
    let remainingFee = {chargeName: '余样处理费', chargeFee: 50, index: 3}
    totalFee = totalFee + 50
    charges.push(remainingFee)
  }
  //3.报告费用
  let selfNum = isNaN(parseInt(form.value.SELF_RECEIVE_NUM)) ? 0 : parseInt(form.value.SELF_RECEIVE_NUM)
  let mailNum = isNaN(parseInt(form.value.MAIL_RECEIVE_NUM)) ? 0 : parseInt(form.value.MAIL_RECEIVE_NUM)
  let reportReceiveNum =  selfNum + mailNum
  if (reportReceiveNum > 2) {
    let reportFee = {chargeName: '报告费用', chargeFee: 20*(reportReceiveNum-2), index: 4}
    totalFee = totalFee + reportFee.chargeFee
    charges.push(reportFee)
  }
  //4.折扣信息
  form.value.PAYMENT_INSPECT_FEES = totalFee
  form.value.PAYMENT_INSPECT_FEES_DISCOUNT = totalFee * form.value.PAYMENT_DISCOUNT * 0.01
  form.value.PAYMENT_INSPECT_FEES_DISCOUNT = form.value.PAYMENT_INSPECT_FEES_DISCOUNT.toFixed(2)
  charges.push({chargeName:'总费用', chargeFee:totalFee, index: 5})
  charges.push({chargeName:'折扣', chargeFee:form.value.PAYMENT_DISCOUNT + '%', index: 6})
  charges.push({chargeName:'应收费用', chargeFee:form.value.PAYMENT_INSPECT_FEES_DISCOUNT, index: 7})
  emit('setting-payment', charges)
}

watch(() => [form.value.INSPECT_CYCLE, form.value.INSPECT_REMAINING_SAMPLE_HANDLE,form.value.SELF_RECEIVE_NUM,
  form.value.MAIL_RECEIVE_NUM, form.value.PAYMENT_DISCOUNT], value=> {
  console.log('-------------------------------------- watch value is :::', value)
  computedFee()
},{deep:true})




//设置报告收取方式
const reportReceiveType = computed(() => {

  return  form.value.REPORT_RECEIVE_TYPE ? form.value.REPORT_RECEIVE_TYPE.split(',') : []
})
const onReceiveTypeChange = (val) =>{
  console.log('check receive type is ::', val)
  if (val.indexOf('自取')> -1){
    if (!form.value.SELF_RECEIVE_NUM||form.value.SELF_RECEIVE_NUM===0){
      form.value.SELF_RECEIVE_NUM = 2
    }
  }else {
    form.value.SELF_RECEIVE_NUM = 0
  }
  if (val.indexOf('邮寄')> -1 ){
    if (!form.value.MAIL_RECEIVE_NUM||form.value.MAIL_RECEIVE_NUM===0){
      form.value.MAIL_RECEIVE_NUM = 2
    }
  }else {
    form.value.MAIL_RECEIVE_NUM = 0
  }
  form.value.REPORT_RECEIVE_TYPE = val.join(',')
}

const workDayList = ref()

const loadWorkDay = () =>{
  let config = new LimsConfig('MM_HOLIDAY_DETAIL')
  let date = new Date()
  config.filters.eq('STATUS','上班')
      .addFilter('DATE_DAY', 'GT', date)
  let childFilter = new LimsFilters()
  childFilter.logic = 'or'
  childFilter.eq('HOLIDAY_ID', date.getFullYear())
  childFilter.eq('HOLIDAY_ID', date.getFullYear()+1)
  config.addChild(childFilter)
  getTableRecord(config).then(response => {
    if (response.success){
      workDayList.value = response.data
    }
  })
}
loadWorkDay()
const onWorkDayNumChange = (val) =>{
  console.log('workDayNumChange:', val)
  let reportDay =workDayList.value[val -1]
  reportDay = reportDay ? reportDay.DATE_DAY : ''
  form.value.REPORT_DATE = reportDay
}
/**
 * 设置工作日
 */
const setWorkDayNum = (id) => {
  urgentOptions.value.find(item => {
    if (item.ID === id) {
      form.value.INSPECT_WORK_DAY_NUM = item.WORK_DAY_NUM
      onWorkDayNumChange(item.WORK_DAY_NUM)
    }
  })
}
const urgentOptions = ref([])
const loadWorkDayOptions = () => {
  let config = new LimsConfig('MM_URGENT')
  config.filters.logic = 'and'
  config.filters.notEq('REMOVE_FLAG', 'T')
  config.addOrderBy('ORDER', 'ASC')
  getTableRecord(config).then(response => {
    if (response.success) {
      urgentOptions.value = response.data
    }
  })
}
loadWorkDayOptions()


const data = reactive({
  rules: {
    INSPECT_SUBJECTS: [{required: true, message: '检验项目必填'}],
    // INSPECT_BASIS_VALUE: [{required: true, message: '检验依据必填'}],
    INSPECT_BASIS: [{required: true, message: '类型必填'}],
    IS_DETERMINE: [{required: true, message: '判定必选'}],
    INSPECT_CYCLE: [{required: true, message: '检测周期必填'}],
    INSPECT_REPORT_APT: [{required: true, message: '检测周期必填'}],
    GROUP_ID: [{required: true, message: '检测组必填'}],
    // REPORT_RECEIVE_TYPE: [{required: true, message: '报告领取方式必填'}],
  },
  options: {
    inspectBasisCJJGList: [],
    urgentList: [],
  },
  reportReceive: {},
  inspectProjectList: [],
})
const {rules, options, reportReceive,} = toRefs(data)
const formInfo = ref()

const handleSubjectChecked = (checkedList) =>{
  console.log('checkedList', checkedList)
  inspectProjectList.value = checkedList
  let arr = checkedList.map(item => item.ORDER_INDEX +'.' + item.INSPECT_SUBJECT)
  form.value.INSPECT_SUBJECTS = arr.join(' ')
  computedFee()
}

watch(() => form.value.SUB_SUBJECTS, value => {
  if (value){
    subProjects.value = value.split(',')
  }
})
const onSubProjectsChange = (value) => {
  form.value.SUB_SUBJECTS = value && value.length > 0 ? value.join(',') :''
}

defineExpose({
  formInfo, inspectProjectList
})
</script>

<template>
  <el-form label-width="120px" ref="formInfo" :model="form" :rules="rules">
    <el-row>
      <el-col :span="24">
        <el-form-item label="检验项目" prop="INSPECT_SUBJECTS">
          <!--            <template #label>-->
          <!--              <el-button type="primary" plain @click="handleSelectSubjects">检验项目</el-button>-->
          <!--            </template>-->
          <el-input type="textarea" v-model="form.INSPECT_SUBJECTS" disabled></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="检验组" prop="GROUP_ID">
          <el-select v-model="form.GROUP_ID" clearable>
            <el-option label="检验室（电塑）" value="JCS_DJ"></el-option>
            <el-option label="检验室（化工）" value="JCS_HG"></el-option>
            <el-option label="检验室（油品）" value="JCS_YP"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-form-item label="检验依据" prop="INSPECT_BASIS_VALUE">
          <el-input v-model="form.INSPECT_BASIS_VALUE" class="input-with-select">
            <template #prepend>
              <el-radio-group v-model="form.INSPECT_BASIS" placeholder="请选择">
                <el-radio label="产品标称" value="产品标称"></el-radio>
                <el-radio label="委托指定" value="委托指定"></el-radio>
                <el-radio label="承检机构确定" value="承检机构确定"></el-radio>
              </el-radio-group>
            </template>
            <template #append>
              <el-button icon="Search" @click="handleSelectInspectBasis"></el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="8">
        <el-form-item label="同意分包" prop="IS_SUB_PACKAGE">
          <el-checkbox label="分包" v-model="form.IS_SUB_PACKAGE">同意</el-checkbox>
        </el-form-item>
      </el-col>
      <el-col :span="16">
        <el-form-item label="分包项目" prop="SUB_SUBJECTS">
          <el-select v-model="subProjects" filterable multiple @change="onSubProjectsChange" :disabled="!form.IS_SUB_PACKAGE">
            <el-option v-for="(item ,index) in inspectProjectList"
                       :key="index"
                       :label="item.INSPECT_SUBJECT"
                       :value="item.INSPECT_SUBJECT"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="16">
        <el-form-item label="检验报告资质" prop="INSPECT_REPORT_APT">
          <wan-feng-select v-model="form.INSPECT_REPORT_APT"
                           table-name="SAMPLE_TYPE"
                           label="NAME"
                           value="[IDENTITY]"
                           where="REMOVEFLAG != 'T'"
                           placeholder="请选择检验报告资质"
          ></wan-feng-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="是否判定" prop="IS_DETERMINE">
          <el-radio v-model="form.IS_DETERMINE" label="是">是</el-radio>
          <el-radio v-model="form.IS_DETERMINE" label="否">否</el-radio>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="16">
        <el-form-item label="检测周期" prop="INSPECT_CYCLE">
          <el-radio-group v-model="form.INSPECT_CYCLE" @change="setWorkDayNum">
            <el-radio v-for="item in urgentOptions"
                      :key="item.ID"
                      :label="item.ID"
            >{{ item.TYPE }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="工作日" prop="INSPECT_WORK_DAY_NUM">
          <el-input-number v-model="form.INSPECT_WORK_DAY_NUM" @change="onWorkDayNumChange" controls-position="right"></el-input-number>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="检毕余样处理" prop="INSPECT_REMAINING_SAMPLE_HANDLE">
          <el-radio-group v-model="form.INSPECT_REMAINING_SAMPLE_HANDLE">
            <el-radio label="自取退回"></el-radio>
            <el-radio label="邮寄退回(邮费到付)"></el-radio>
            <el-radio label="承检机构处理(需收取50元样品处理费)"></el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="6">
        <el-form-item label="报告出具时间" prop="REPORT_DATE">
          <el-date-picker v-model="form.REPORT_DATE" disabled type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-form-item label="报告领取方式" prop="REPORT_RECEIVE_TYPE">
          <el-checkbox-group v-model="reportReceiveType" @change="onReceiveTypeChange">
            <el-row :gutter="20">
              <el-col :span="2">
                <el-checkbox label="自取"></el-checkbox>
              </el-col>
              <el-col :span="6">
                <el-input class="el-input-number" v-model="form.SELF_RECEIVE_NUM" @input="computedFee">
                  <template #prepend="">一式</template>
                  <template #append>份</template>
                </el-input>
              </el-col>
              <el-col :span="2">
                <el-checkbox label="邮寄"></el-checkbox>
              </el-col>
              <el-col :span="6">
                <el-input class="el-input-number" v-model="form.MAIL_RECEIVE_NUM" @input="computedFee">
                  <template #prepend="">一式</template>
                  <template #append>份</template>
                </el-input>
              </el-col>
              <el-col :span="6">
                <el-checkbox label="电子报告"></el-checkbox>
              </el-col>
            </el-row>
          </el-checkbox-group>
          <div>
            <span>（说明：纸质检验报告一式两份，<b>如需增加，按20元/份额外收取费用</b>）</span>
          </div>
        </el-form-item>

      </el-col>
    </el-row>
    <el-row>
      <el-col :span="8">
        <el-form-item label="检验费用" prop="PAYMENT_INSPECT_FEES">
          <el-input v-model="form.PAYMENT_INSPECT_FEES" disabled>
            <template #append>
              <span>元</span>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="费用折扣" prop="PAYMENT_DISCOUNT">
          <el-input type="number" :step="10" :min="0" v-model="form.PAYMENT_DISCOUNT" >
            <template #append>
              <el-button> %</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="折扣后费用" prop="PAYMENT_INSPECT_FEES_DISCOUNT">
          <el-input v-model="form.PAYMENT_INSPECT_FEES_DISCOUNT" disabled>
            <template #append>
<!--              <el-button @click="computedFee" type="primary">计算</el-button>-->
              <span>元</span>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <el-divider>检验项目</el-divider>
  <subject-table :order-id="form.ORDER_ID" @checked="handleSubjectChecked"></subject-table>
  <select-inspect-basis ref="inspectBasisTable" :title="'选择'+form.INSPECT_BASIS"
                        @ok="selectedInspectBasis"></select-inspect-basis>
</template>

<style scoped lang="scss">

</style>